<template>
  <ul class="xitongYonghu" style="z-index: 1">
    <li class="xitongYonghu-top">
      <ul class="xitong-search" style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">
        <div class="search-group" style="display: flex;align-items: center;">
          <el-input
              v-model="searchAll"
              placeholder="请输入咨询师全名进行搜索"
              style="width: 300px;margin-right: 10px"
              clearable
              @keyup.enter="serchBtn"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button
              type="primary"
              @click="serchBtn"
              :loading="isSearching"
          >
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSerchbtn">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </ul>

      <!-- 咨询师列表 -->
      <li>
        <el-table
          ref="tableRef"
          :data="itemsArr"
          style="width: 100%"
          border
          v-loading="isLoading"
        >
          <el-table-column prop="consultantId" label="ID" width="80" />
          <el-table-column prop="consultantName" label="咨询师名称" width="120" />
          <el-table-column prop="consultantAvatar" label="头像" width="100">
            <template #default="scope">
              <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.consultantAvatar"
                :preview-src-list="[scope.row.consultantAvatar]"
                fit="cover"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="fullName" label="全名" width="120" />
          <el-table-column prop="consultantAge" label="年龄" width="80">
            <template #default="scope">
              {{ scope.row.consultantAge }}岁
            </template>
          </el-table-column>
          <el-table-column prop="consultantGender" label="性别" width="80" />
          <el-table-column prop="consultantPhone" label="电话" width="120" />
          <el-table-column prop="consultantAddress" label="地址" width="180" />
          <el-table-column prop="consultantLevelId" label="等级" width="100">
            <template #default="scope">
              {{ getLevelName(scope.row.consultantLevelId) }}
            </template>
          </el-table-column>
          <el-table-column prop="consultantDesc" label="简介" width="200" show-overflow-tooltip />
          <el-table-column prop="consultantIntroduction" label="详细介绍" width="300" show-overflow-tooltip />
        </el-table>

        <!-- 分页器 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination"
        />
      </li>
    </li>
  </ul>
</template>

<script setup>
import { computed, ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Search, Refresh, Picture } from '@element-plus/icons-vue'

// 控制咨询师列表显示隐藏
const isShow = ref(true)
// 搜索框输入内容
const searchAll = ref('') 
const isSearching = ref(false)

// 分页相关的响应式变量声明
const currentPage = ref(1)    
const pageSize = ref(5)       
const total = ref(0)
const itemsArr = ref([])      
const isLoading = ref(false)

const tableRef = ref(null)   

// 添加选中行的响应式变量
const selectedRows = ref([])

// 获取咨询师列表
const getConsultantList = async () => {
  try {
    isLoading.value = true
    const response = await axios.get('http://localhost:8080/consultants/selectAllConsultants', {
      params: {
        pageNo: currentPage.value,
        pageSize: pageSize.value
      }
    })

    if (response.status === 200) {
      itemsArr.value = response.data
      total.value = 70  // 修改为实际的总数据量70条
      currentPage.value = currentPage.value || 1
      pageSize.value = pageSize.value || 5
      isShow.value = true
    } else {
      throw new Error('获取数据失败')
    }
  } catch (error) {
    console.error('获取咨询师列表失败:', error)
    ElMessage.error('获取咨询师列表失败')
    itemsArr.value = []
    total.value = 0
  } finally {
    isLoading.value = false
  }
}

// 处理每页显示数量变化
const handleSizeChange = async (size) => {
  try {
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    selectedRows.value = []

    pageSize.value = size
    currentPage.value = 1

    // 根据是否在搜索状态决定调用哪个接口
    if (searchAll.value.trim()) {
      await serchBtn()
    } else {
      await getConsultantList()
    }
  } catch (error) {
    console.error('切换页面大小失败:', error)
  }
}

// 处理当前页码变化
const handleCurrentChange = async (page) => {
  try {
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    selectedRows.value = []

    currentPage.value = page

    // 根据是否在搜索状态决定调用哪个接口
    if (searchAll.value.trim()) {
      await serchBtn()
    } else {
      await getConsultantList()
    }
  } catch (error) {
    console.error('切换页码失败:', error)
  }
}

// 搜索按钮点击事件
const serchBtn = async () => {
  try {
    if (!searchAll.value.trim()) {
      ElMessage.warning('请输入咨询师全名')
      return
    }
    console.log(searchAll.value.trim())

    isSearching.value = true
    // 搜索时重置到第一页
    currentPage.value = 1
    
    const response = await axios.get('http://localhost:8080/consultants/selectConsultantsByLike', {
      params: {
        name: searchAll.value.trim(),
        pageNo: currentPage.value,
        pageSize: pageSize.value
      }
    })

    if (response.status === 200) {
      itemsArr.value = response.data
      // 如果是搜索结果，使用实际的数据长度作为总数
      total.value = response.data.length
      isShow.value = true
      
      if (response.data.length > 0) {
        ElMessage.success(`找到 ${response.data.length} 条匹配记录`)
      } else {
        ElMessage.info('未找到匹配的咨询师')
      }
    } else {
      throw new Error('搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
    itemsArr.value = []
    total.value = 0
  } finally {
    isSearching.value = false
  }
}

// 重置搜索按钮点击事件
const resetSerchbtn = async () => {
  try {
    searchAll.value = ''
    currentPage.value = 1
    pageSize.value = 5
    isSearching.value = false
    await getConsultantList()
    total.value = 70  // 重置回总数据量
    ElMessage.success('已重置')
  } catch (error) {
    console.error('重置失败:', error)
    ElMessage.error('重置失败，请稍后重试')
  }
}

// 页面加载时获取数据
onMounted(async () => {
  try {
    await getConsultantList()
  } catch (error) {
    console.error('初始化加载失败:', error)
    ElMessage.error('初始化加载失败')
  }
})

// 添加等级映射函数
const getLevelName = (levelId) => {
  const levelMap = {
    1: '初级咨询师',
    2: '中级咨询师', 
    3: '高级咨询师'
  }
  return levelMap[levelId] || '未知等级'
}

</script>

<style scoped>
.avatar-uploader {
  text-align: center;
}

.avatar-wrapper {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  padding: 8px;
  margin-bottom: 8px;
  transition: border-color 0.3s;
}

.avatar-wrapper:hover {
  border-color: #409EFF;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-pagination) {
  margin-top: 20px;
  justify-content: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>